//
//  CZUserAccount.swift
//  XLWB009
//
//  Created by apple on 3/24/16.
//  Copyright © 2016 apple. All rights reserved.
//

import UIKit

//归档需要实现NSCoding协议
class CZUserAccount: NSObject,NSCoding{

    var access_token:String?	//用于调用access_token，接口获取授权后的access token。
    //access_token的生命周期，单位是秒数。
    var expires_in:NSTimeInterval=0{
        didSet{
            expiresDate=NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var uid:String?	//当前授权用户的UID。
    
    //用户名称
    var screen_name:String?
    
    //用户头像地址
    var avatar_large:String?
    
    var expiresDate:NSDate?//生命周期时间，方便系统处理时间
    
    //使用KVC字典转模型
    init(dict:[String:AnyObject]){
        //没有定义super.init()之前赋值，需要定义为可选
        super.init()
        
        //使用KVC赋值
        setValuesForKeysWithDictionary(dict)
    }
    
    //字典中的key在模型中找不到对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print("forkey:",key)
    }
    
    //实现对象打印
    override var description:String{
    
        let keys=["access_token","expires_in","uid","expiresDate"]
        return dictionaryWithValuesForKeys(keys).description
//        get{
//            return "access_token:\(access_token),expires_in:\(expires_in),uid:\(uid)"
//        }
    }
    
    //归档和解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token,forKey:"access_token")
        aCoder.encodeObject(uid,forKey:"uid")
        aCoder.encodeDouble(expires_in, forKey:"expires_in")
        aCoder.encodeObject(expiresDate,forKey:"expiresDate")
    }
    
    //解档
    required init?(coder aDecoder:NSCoder){
        super.init()
        access_token=aDecoder.decodeObjectForKey("access_token")as? String
        uid=aDecoder.decodeObjectForKey("uid")as? String
        expires_in=aDecoder.decodeDoubleForKey("expires_in")
        expiresDate=aDecoder.decodeObjectForKey("expiresDate")as? NSDate
    }
}
